"""
本脚本用于自动打包版本:
    1.双击运行本脚本，输入版本号，自动打包版本所需文件到 output
    2.手动打开 校验码查看工具_2.1.6.exe 添加 .fw 校验码
"""


import os
import shutil
import zipfile
import time
import pathlib
import win32api
import psutil



VER_BASE_NAME = "1.1.0_0000"
PROJECT_NAME = "D8B301-"
CHECK_CODE_FILE = "固件校验码：xxxx-xxxxxxxx.txt"
OUTPUT_PATH_DEVELOP = "开发固件"
OUTPUT_PATH_FACTORY = "量产固件"
CRC_SW_NAME = "校验码查看工具_2.1.6.exe"

OUTPUT_PATH = "output"
APP_BIN = "app.bin"
OTA_BIN = "update.ufw"
FACTORY_BIN = "jl_isd.fw"
RELEASE_LOG = "readme.txt"
SRC_FILE_DEVELOP = (APP_BIN, OTA_BIN)
SRC_FILE_FACTORY = (OTA_BIN, FACTORY_BIN)

OUTPUT_PATH_NO_KEY = "no_key"
OUTPUT_PATH_001 = "001"
OUTPUT_PATH_088 = "088"
OUTPUT_PATH_056 = "056"
BUILD_CMD_NO_KEY = "..\\cpu\\bd19\\tools\\download\\data_trans\\download.bat"
BUILD_CMD_001 = "..\\cpu\\bd19\\tools\\download\\data_trans\\download-key-001.bat"
BUILD_CMD_088 = "..\\cpu\\bd19\\tools\\download\\data_trans\\download-key-088.bat"
BUILD_CMD_560 = "..\\cpu\\bd19\\tools\\download\\data_trans\\download-key-560.bat"
BUILD_CMD = ((OUTPUT_PATH_001, BUILD_CMD_001), (OUTPUT_PATH_088, BUILD_CMD_088))
OUTPUT_PATH_KEY_LAST_NAME = "-key"



# 清空文件夹
def system_makedir(path):
    if os.path.exists(path):
        shutil.rmtree(path)
    os.makedirs(path)


# 模糊搜索
def system_fuzzy_search(path, file):
    total_file_name = None
    file_list = os.listdir(path)
    for i in file_list:
        if i.find(file) >= 0:
            total_file_name = i
            break
    return total_file_name


# 检查文件是否都存在，返回完整路径
def system_check_file_list_exist(path, src_list):
    total_path_list = []
    for i in range(len(src_list)):
        file_total_name = system_fuzzy_search(path, src_list[i])
        if file_total_name == None:
            print("error : no %s bin." % src_list[i])
            os.system("pause")
            exit()
        else:
            total_path_list.append(path + os.sep + file_total_name)
    return total_path_list


# 打包目录为zip文件
def system_make_zip(source_dir, output_filename):
    zipf = zipfile.ZipFile(output_filename, 'w')
    pre_len = len(os.path.dirname(source_dir))
    for parent, dirnames, filenames in os.walk(source_dir):
        for filename in filenames:
            print(filename)
            pathfile = os.path.join(parent, filename)
            arcname = pathfile[pre_len:].strip(os.path.sep)  # 相对路径
            zipf.write(pathfile, arcname)
        print()
    zipf.close()


# 打开某个应用
def SystemProcessRun(SWPath):
    win32api.ShellExecute(0, "open", SWPath, "", "", 1)
    time.sleep(3)

# 关闭某个应用
def SystemProcessExit(SWName):
    pl = psutil.pids()
    for pid in pl:
        if psutil.Process(pid).name() == SWName:
            TotalCmd = r"taskkill /F /IM " + SWName
            os.system(TotalCmd)
            break




# main函数
if __name__ == '__main__':
    if not os.path.exists(OUTPUT_PATH):
        os.makedirs(OUTPUT_PATH)

    # 创建文件夹
    version = input("Input Version :")
    version_total_name = PROJECT_NAME + VER_BASE_NAME[:-len(version)] + version
    version_folder_name = OUTPUT_PATH + os.sep + version_total_name
    system_makedir(version_folder_name)

	# 复制readme
    shutil.copy(RELEASE_LOG, version_folder_name)

    # 开发固件
    # 启动生成固件的脚本
    os.system(BUILD_CMD_NO_KEY)
    # 检查文件是否都存在
    total_path_list = system_check_file_list_exist(".", SRC_FILE_DEVELOP)
    # 创建文件夹
    output_path_key = version_folder_name + os.sep + OUTPUT_PATH_DEVELOP
    system_makedir(output_path_key)
    for i in range(len(total_path_list)):
        # 重命名
        file_path = os.path.dirname(total_path_list[i]) 
        file_type = os.path.splitext(total_path_list[i])[1]
        file_total_name_new = file_path + os.sep + version_total_name + file_type
        os.rename(total_path_list[i], file_total_name_new)
        # 移动文件
        shutil.move(file_total_name_new, output_path_key)


# 临时注释
def volume_production():
    # 量产固件
    for i in range(len(BUILD_CMD)):
        # 启动生成固件的脚本
        os.system(BUILD_CMD[i][1])
        # 检查文件是否都存在
        total_path_list = system_check_file_list_exist(".", SRC_FILE_FACTORY)
        # 创建文件夹
        output_path_key = version_folder_name + os.sep + OUTPUT_PATH_FACTORY + os.sep + version_total_name + "-" + BUILD_CMD[i][0] + OUTPUT_PATH_KEY_LAST_NAME
        system_makedir(output_path_key)
        # 复制文件
        for j in range(len(total_path_list)):
            # 重命名
            file_path = os.path.dirname(total_path_list[j]) 
            file_type = os.path.splitext(total_path_list[j])[1]
            file_total_name_new = file_path + os.sep + version_total_name + "-" + BUILD_CMD[i][0] + OUTPUT_PATH_KEY_LAST_NAME + file_type
            os.rename(total_path_list[j], file_total_name_new)
            # 移动文件
            shutil.move(file_total_name_new, output_path_key)
            # 创建校验码文件
            pathlib.Path(output_path_key + os.sep + CHECK_CODE_FILE).touch()

    # 准备手动添加校验码
    SystemProcessExit(CRC_SW_NAME)
    SystemProcessRun(CRC_SW_NAME)

